package formbean;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import utility.Util_Img;
import databean.ItemBean;

public class ReviseItemForm {
	private final static String file_path = "c://mine/file/";

	public static ItemBean parse(HttpServletRequest request) {

		// get data from form
		HashMap<String, String> hash = new HashMap<String, String>();
		HashMap<String, FileItem> fhash = new HashMap<String, FileItem>();
		boolean ifMult = ServletFileUpload.isMultipartContent(request);
		if (ifMult) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {

				e.printStackTrace();
			}
			if (items != null && items.size() > 0) {
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();

					if (item.isFormField()) {
						// case text field
						String name = item.getFieldName();
						String value = item.getString();
						hash.put(name, value);
					} else {
						// case file
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						hash.put(fieldName, fileName);
						fhash.put(fieldName, item);

					}

				}
				// now every information is in hash, try to put them in to bean
				// and upload image to ebay
				FileItem fimg = fhash.get("image");
				String f_name = hash.get("image");
				File tmp = new File(file_path+f_name);
				try {
					tmp.createNewFile();
					fimg.write(tmp);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String pic_url = null;

				pic_url = Util_Img.upload(tmp);

				ItemBean item = new ItemBean();
				String title = hash.get("title");
				String description = hash.get("description");
				String price = hash.get("price");
				String buyItNowPrice = hash.get("buyItNowPrice");
				String id=hash.get("id");
				item.setItemID(id);
				item.setTitle(title);
				item.setDescription(description);
				item.setStartPrice(price);
				item.setBuyItNowPrice(buyItNowPrice);
				
				item.setPictureURL(pic_url);
				return item;
			}
		}
		return null;
	}
}
